{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "ename": "ModuleNotFoundError",
     "evalue": "No module named 'spacy'",
     "output_type": "error",
     "traceback": [
      "\u001B[1;31m---------------------------------------------------------------------------\u001B[0m",
      "\u001B[1;31mModuleNotFoundError\u001B[0m                       Traceback (most recent call last)",
      "\u001B[1;32m<ipython-input-3-e308fa9950a4>\u001B[0m in \u001B[0;36m<module>\u001B[1;34m\u001B[0m\n\u001B[1;32m----> 1\u001B[1;33m \u001B[1;32mimport\u001B[0m \u001B[0mspacy\u001B[0m\u001B[1;33m\u001B[0m\u001B[1;33m\u001B[0m\u001B[0m\n\u001B[0m\u001B[0;32m      2\u001B[0m \u001B[1;32mfrom\u001B[0m \u001B[0msklearn\u001B[0m\u001B[1;33m.\u001B[0m\u001B[0mbase\u001B[0m \u001B[1;32mimport\u001B[0m \u001B[0mTransformerMixin\u001B[0m\u001B[1;33m\u001B[0m\u001B[1;33m\u001B[0m\u001B[0m\n\u001B[0;32m      3\u001B[0m \u001B[1;33m\u001B[0m\u001B[0m\n\u001B[0;32m      4\u001B[0m \u001B[1;31m# Create a spaCy parser\u001B[0m\u001B[1;33m\u001B[0m\u001B[1;33m\u001B[0m\u001B[1;33m\u001B[0m\u001B[0m\n\u001B[0;32m      5\u001B[0m \u001B[0mnlp\u001B[0m \u001B[1;33m=\u001B[0m \u001B[0mspacy\u001B[0m\u001B[1;33m.\u001B[0m\u001B[0mload\u001B[0m\u001B[1;33m(\u001B[0m\u001B[1;34m'en'\u001B[0m\u001B[1;33m)\u001B[0m\u001B[1;33m\u001B[0m\u001B[1;33m\u001B[0m\u001B[0m\n",
      "\u001B[1;31mModuleNotFoundError\u001B[0m: No module named 'spacy'"
     ]
    }
   ],
   "source": [
    "import spacy\n",
    "from sklearn.base import TransformerMixin\n",
    "\n",
    "# Create a spaCy parser\n",
    "nlp = spacy.load('en')\n",
    "\n",
    "\n",
    "class BagOfWords(TransformerMixin):\n",
    "    def fit(self, X, y=None):\n",
    "        return self\n",
    "    \n",
    "    def transform(self, X):\n",
    "        results = []\n",
    "        for document in X:\n",
    "            row = {}\n",
    "            for word in list(nlp(document, tag=False, parse=False, entity=False)):\n",
    "                if len(word.text.strip()):\n",
    "                    row[word.text] = True\n",
    "            results.append(row)\n",
    "        return results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from sklearn.feature_extraction import DictVectorizer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from sklearn.naive_bayes import BernoulliNB"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# https://www.freesion.com/article/8487261831/\n",
    "import os\n",
    "input_filename = os.path.join(os.path.expanduser(\"~\"), \"data/datasets\", \"twitter\", \"python_tweets.json\")\n",
    "labels_filename = os.path.join(os.path.expanduser(\"~\"), \"data/datasets\", \"twitter\", \"python_classes.json\")\n",
    "\n",
    "input_filename = \"python_tweets.json\"\n",
    "labels_filename = \"python_classes.json\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import json\n",
    "\n",
    "tweets = []\n",
    "with open(input_filename) as inf:\n",
    "    for line in inf:\n",
    "        if len(line.strip()) == 0: continue\n",
    "        tweets.append(json.loads(line)['text'])\n",
    "\n",
    "with open(labels_filename) as inf:\n",
    "    labels = json.load(inf)\n",
    "\n",
    "# Ensure only classified tweets are loaded\n",
    "tweets = tweets[:len(labels)]\n",
    "assert len(tweets) == len(labels)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from sklearn.pipeline import Pipeline\n",
    "\n",
    "pipeline = Pipeline([('bag-of-words', BagOfWords()), ('vectorizer', DictVectorizer()), ('naive-bayes', BernoulliNB()) ])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# from sklearn.cross_validation import cross_val_score\n",
    "from sklearn.model_selection import cross_val_score\n",
    "scores = cross_val_score(pipeline, tweets, labels, scoring='f1')\n",
    "#We then print out the average of the scores:\n",
    "import numpy as np\n",
    "print(\"Score: {:.3f}\".format(np.mean(scores)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "model = pipeline.fit(tweets, labels)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "nb = model.named_steps['naive-bayes']\n",
    "feature_probabilities = nb.feature_log_prob_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "top_features = np.argsort(-nb.feature_log_prob_[1])[:50]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "dv = model.named_steps['vectorizer']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "for i, feature_index in enumerate(top_features):\n",
    "    print(i, dv.feature_names_[feature_index], np.exp(feature_probabilities[1][feature_index]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}